//
//  SCBottomPopAlertVC.m
//  PhotoAlbum
//
//  Created by Chao Sheng on 2021/12/8.
//

#import "SCBottomPopAlertVC.h"

@implementation SCBottomPopAction

- (SCBottomPopAction*)actionWithTitle:(NSString *)title ActionType:(SCBottomPopActionType)type SelectHandler:(void (^)(void))selectHandler {
    
    SCBottomPopAction *action = [[SCBottomPopAction alloc] init];
    action.type = type;
    action.title = title;
    action.SCBottomPopSelectHandler = selectHandler;
    
    return action;
}

@end

@interface SCBottomPopItemView : UIButton

@property(nonatomic,strong) UIToolbar * toolbar;
@property(nonatomic,strong) UIView * bottomLine;
@property(nonatomic,strong) NSString * title;
@property(nonatomic,copy) dispatch_block_t clickBlock;
@property(nonatomic,assign) SCBottomPopActionType type;

@end

@implementation SCBottomPopItemView

- (instancetype)initWithFrame:(CGRect)frame withType:(SCBottomPopActionType)type{
    if(self = [super initWithFrame:frame]){
        _type = type;
        [self addSubview:self.toolbar];
        [self addSubview:self.bottomLine];
        self.titleLabel.font = [UIFont systemFontOfSize:17];
        [self addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
        self.backgroundColor = [UIColor whiteColor];
    }
    
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.toolbar.frame = self.bounds;
}

- (void)setTitle:(NSString *)title{
    _title = title;
    [self setTitle:_title forState:UIControlStateNormal];
}

- (UIView *)bottomLine{
    if (!_bottomLine) {
        _bottomLine = [[UIView alloc]init];
        _bottomLine.frame = CGRectMake(0, CGRectGetHeight(self.frame)-1, CGRectGetWidth(self.frame), 1);
        _bottomLine.backgroundColor = [UIColor blackColor];
        _bottomLine.alpha = 0.1;
    }
    return _bottomLine;
}

- (UIToolbar *)toolbar {
    if (!_toolbar) {
        _toolbar = [[UIToolbar alloc] init];
        _toolbar.translucent = true;
        _toolbar.barTintColor = nil;
        _toolbar.userInteractionEnabled = false;
    }
    return _toolbar;
}

- (void)action:(UIButton *)sender{
    if (self.clickBlock) {
        self.clickBlock();
    }
}

@end

@interface SCBottomPopAlertVC ()<UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning>

@property (nonatomic,strong) UITapGestureRecognizer *tapGesture;
@property (nonatomic,strong) UIView *maskView;
@property (nonatomic,strong) UIView *popupView;

@property(nonatomic,strong)NSMutableArray <SCBottomPopAction *>* actionArray;//action数组
@property(nonatomic,assign)BOOL isContainCancel;//是否包含取消

@end

@implementation SCBottomPopAlertVC

- (instancetype)init {
    if (self = [super init]) {
        self.transitioningDelegate = self;
        self.modalPresentationStyle = UIModalPresentationCustom;
         _actionArray = @[].mutableCopy;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUpUI];
}

- (void)setUpUI {
    
    [self.view addSubview:self.maskView];
    [self.view addSubview:self.popupView];
    
    [self setupSubViews];
    self.popupView.backgroundColor = [UIColor clearColor];
}

- (void)setupSubViews {
    UIView * popupView = self.popupView;
    for (SCBottomPopAction * action in self.actionArray) {
        if (action.type == SCBottomPopActionCancelType) {//如果等于取消;
            //将action 移动到数组末尾
            [self.actionArray removeObject:action];
            [self.actionArray addObject:action];
        }
    }
    
    CGFloat itemH = 60;
    
    UIView *topPopView = [[UIView alloc] initWithFrame:self.popupView.bounds];
    [self.popupView addSubview:topPopView];
    topPopView.layer.cornerRadius = 10;
    topPopView.layer.masksToBounds = YES;
    if(self.isContainCancel) {
        CGRect frame = CGRectMake(topPopView.frame.origin.x, topPopView.frame.origin.y, topPopView.frame.size.width, (self.actionArray.count-1)*itemH);
        topPopView.frame = frame;
    }
    for (int i = 0; i < self.actionArray.count; i++) {
        
        SCBottomPopAction *action = self.actionArray[i];
        SCBottomPopItemView * sv;
        sc_weak(self);
        if (action.type ==  SCBottomPopActionCancelType) {
            UIView *svContainView = [[UIView alloc]initWithFrame:CGRectMake(0, i*itemH + 10, CGRectGetWidth(popupView.frame),itemH)];
            svContainView.layer.cornerRadius = 10;
            svContainView.layer.masksToBounds = YES;
            sv = [[SCBottomPopItemView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(popupView.frame), itemH) withType:action.type];
            sv.backgroundColor = [UIColor whiteColor];
            sv.bottomLine.hidden = YES;
            sv.titleLabel.font = [UIFont systemFontOfSize:17];
            [sv setTitleColor:[UIColor colorWithRed:102/255.0 green:102/255.0  blue:102/255.0  alpha:1] forState:UIControlStateNormal];
            sv.clickBlock = ^{
                
                 [weakself dismiss];
                
                 if (action.SCBottomPopSelectHandler) {
                     action.SCBottomPopSelectHandler();
                 }
            };
            svContainView.backgroundColor = [UIColor whiteColor];
            [svContainView addSubview:sv];
            [popupView addSubview:svContainView];
            
         }else{
             
            sv = [[SCBottomPopItemView alloc]initWithFrame:CGRectMake(0, i*itemH, CGRectGetWidth(popupView.frame), itemH) withType:action.type];
            sv.backgroundColor = [UIColor whiteColor];
            sv.bottomLine.hidden = NO;
             [sv setTitleColor:[UIColor colorWithRed:0/255.0 green:153/255.0  blue:255/255.0  alpha:1] forState:UIControlStateNormal];
            sv.clickBlock = ^{
                
                [weakself dismiss];
                
                if (action.SCBottomPopSelectHandler) {
                    action.SCBottomPopSelectHandler();
                }
            };
            [topPopView addSubview:sv];
         }
        
         sv.title = action.title;
    }
}

#pragma mark - getter
- (UIView *)popupView {
    if (!_popupView) {
        _popupView = [[UIView alloc] initWithFrame:CGRectMake(10,sc_HEIGHT-(self.actionArray.count*60+20)-sc_BOTTOMPADDING_HEIGHT, sc_WIDTH-20, self.actionArray.count*60+20+sc_BOTTOMPADDING_HEIGHT)];
        _popupView.backgroundColor = [UIColor whiteColor];
        _popupView.layer.cornerRadius = 10;
        _popupView.layer.masksToBounds = YES;
    }
    return _popupView;
}

- (UIView *)maskView {
    if (!_maskView) {
        _maskView = [[UIView alloc] initWithFrame:self.view.bounds];
        _maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        [_maskView addGestureRecognizer:self.tapGesture];
    }
    return _maskView;
}

- (UITapGestureRecognizer *)tapGesture {
    if (!_tapGesture) {
        _tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    }
    return _tapGesture;
}

#pragma mark - public method
- (void)dismiss {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dismissWithCompletion:(void (^)(void))completion {
    [self dismissViewControllerAnimated:YES completion:completion];
}

- (void)addAction:(SCBottomPopAction *)action {
    if (![self.actionArray containsObject:action]) {
        
        if (self.isContainCancel == YES) {
            return;
        }
        
        if (action.type==SCBottomPopActionCancelType && self.isContainCancel==NO) {
            self.isContainCancel = YES;
        }
        
        [self.actionArray addObject:action];
    }
}

#pragma mark - selector
- (void)tapAction:(UIGestureRecognizer*)tap {
    [self dismiss];
}

#pragma mark - UIViewControllerAnimatedTransitioning
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return 0.6;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];

    UIView *containView = [transitionContext containerView];
    //显示关键代码
    if (_animatingType==SCPopupAnimatingTypePresent) {

        UIView *popedView = ((SCBottomPopAlertVC *)toVC).popupView;
        [containView addSubview:toVC.view];
        popedView.alpha = 0;
        CGRect frame = popedView.frame;
        frame.origin = CGPointMake(10, CGRectGetHeight(self.view.frame));
        popedView.frame = frame;
        
        NSTimeInterval duration = [self transitionDuration:transitionContext];
        [UIView animateWithDuration:duration / 2.0 animations:^{
            popedView.alpha = 1.0;
        }];
        
        [UIView animateWithDuration:duration / 2.0 animations:^{
            popedView.transform = CGAffineTransformMakeTranslation(0, -CGRectGetHeight(popedView.frame));
        } completion:^(BOOL finished) {
            //这样的是为了如中途取消可设置为未完成，这样可恢复原状
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        }];


    } else {

        UIView *popedView = ((SCBottomPopAlertVC *)fromVC).popupView;
        
        NSTimeInterval duration = [self transitionDuration:transitionContext];
        [UIView animateWithDuration:duration/2 animations:^{
            popedView.transform = CGAffineTransformMakeTranslation(0,CGRectGetHeight(popedView.frame));
            popedView.alpha = 0;
        } completion:^(BOOL finished) {
            [transitionContext completeTransition:YES];
        }];


    }
    
}

#pragma mark - UIViewControllerTransitioningDelegate
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    
    _animatingType = SCPopupAnimatingTypePresent;
    
    return self;
}

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    
    _animatingType = SCPopupAnimatingTypeDismiss;

    return self;
}

- (void)dealloc{
    NSLog(@"dealloc__func__=%s",__func__);
}

@end

